<?php
class SiteConfig extends Model{
    private static $_config = null;
    private static $_instance = null;
    
    public function init(){$this->OpenDB();}

    public static function get($key){

        if(empty(self::$_config)){
            self::$_config = self::getInstance()->loadConfig();
        }
        if(self::$_config[$key]){
            return self::$_config[$key];
        }
        return null;
    }
    /**
     * get all site config
     */
    public static function getAll(){
    	if(empty(self::$_config)){
            self::$_config = self::getInstance()->loadConfig();
        }
        return self::$_config;
    }
    
    public static function getInstance(){
    	if(empty(self::$_instance)){
    		self::$_instance = new self();
    	}
    	return self::$_instance;
    }

    public function loadConfig(){
        return $this->db->get_one('SELECT * FROM @#__config LIMIT 1');
    }

    public function set($key,$value){
        self::$_config[$key] = $value;
        return $this;
    }

    public function save(){
        $param = array();
        foreach(self::$_config as $key=>$value){
            $param[] = $key.'=\''.str_replace("'","''",$value).'\'';
        }
        $sql = "UPDATE @#__config SET ".join(',',$param) ." LIMIT 1";
        return (boolean)$this->db->query($sql);
    }
}